package com.shitou.springai1.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shitou.springai1.admin.entity.dto.CustomUserDetailsDto;
import com.shitou.springai1.admin.entity.dto.UserDto;
import com.shitou.springai1.admin.mapper.UserMapper;
import com.shitou.springai1.admin.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDto> implements UserService, UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("=== UserServiceImpl.loadUserByUsername() 开始 ===");
        System.out.println("🔍 正在查询用户，用户名/学号: " + username);

        // 从数据库中查询用户信息
        UserDto userDto = baseMapper.selectOne(new LambdaQueryWrapper<UserDto>()
                .eq(UserDto::getStuOrTeaId, username));

        if (userDto == null) {
            System.out.println("❌ 用户不存在: " + username);
            System.out.println("=== UserServiceImpl.loadUserByUsername() 结束 - 用户不存在 ===");
            throw new UsernameNotFoundException("用户不存在");
        }

        // 详细打印用户信息
        System.out.println("✅ 用户查询成功！");
        System.out.println("📋 用户详细信息:");
        System.out.println("   - 学号/教师号: " + userDto.getStuOrTeaId());
        System.out.println("   - 数据库密码: " + userDto.getUserPass());
        System.out.println("   - 账号状态: " + userDto.getAccountStatus() + " (类型: " + userDto.getAccountStatus().getClass().getSimpleName() + ")");
        System.out.println("   - 用户角色: " + userDto.getRole());
        System.out.println("   - 用户ID: " + userDto.getId());

        // 检查账号状态
        boolean accountEnabled;
        try {
            if (userDto.getAccountStatus() instanceof Integer) {
                accountEnabled = userDto.getAccountStatus().equals(1);
                System.out.println("📊 账号状态比较 (Integer): " + userDto.getAccountStatus() + " == 1 -> " + accountEnabled);
            } else {
                accountEnabled = "1".equals(String.valueOf(userDto.getAccountStatus()));
                System.out.println("📊 账号状态比较 (其他类型): " + userDto.getAccountStatus() + " == \"1\" -> " + accountEnabled);
            }
        } catch (Exception e) {
            System.out.println("⚠️ 账号状态检查异常: " + e.getMessage());
            accountEnabled = false;
        }

        // 获取权限
        Collection<? extends GrantedAuthority> authorities = getAuthorities(userDto.getRole());

        // 创建自定义的UserDetails对象
        CustomUserDetailsDto customUserDetailsDto = new CustomUserDetailsDto(
                userDto,
                userDto.getUserPass(),
                authorities
        );

        System.out.println("🎯 创建的CustomUserDetails:");
        System.out.println("   - 用户名: " + customUserDetailsDto.getUsername());
        System.out.println("   - 密码: " + customUserDetailsDto.getPassword());
        System.out.println("   - 账号是否启用: " + customUserDetailsDto.isEnabled());
        System.out.println("   - 包含的UserDto: " + (customUserDetailsDto.getUserDto() != null ? "有" : "无"));

        System.out.println("=== UserServiceImpl.loadUserByUsername() 结束 - 成功 ===");
        return customUserDetailsDto;
    }

    private Collection<? extends GrantedAuthority> getAuthorities(String role) {
        System.out.println("🎭 开始处理用户角色: " + role);
        List<GrantedAuthority> authorities = new ArrayList<>();

        // 如果角色为空，返回空集合
        if (role == null || role.trim().isEmpty()) {
            System.out.println("⚠️ 用户角色为空，将返回空权限列表");
            return authorities;
        }

        System.out.println("🔧 原始角色字符串: " + role);

        // 处理多个角色的情况（假设角色以逗号分隔）
        String[] roles = role.split(",");
        System.out.println("🔧 分割后的角色数量: " + roles.length);

        for (int i = 0; i < roles.length; i++) {
            String r = roles[i];
            // 去除前后空格
            String trimmedRole = r.trim();
            System.out.println("🔧 处理第 " + (i+1) + " 个角色: '" + r + "' -> '" + trimmedRole + "'");

            if (!trimmedRole.isEmpty()) {
                // Spring Security要求角色以"ROLE_"开头
                String finalRole = trimmedRole;
                if (!trimmedRole.startsWith("ROLE_")) {
                    finalRole = "ROLE_" + trimmedRole;
                    System.out.println("🔧 添加ROLE_前缀: '" + trimmedRole + "' -> '" + finalRole + "'");
                }

                System.out.println("✅ 添加角色权限: " + finalRole);
                authorities.add(new SimpleGrantedAuthority(finalRole));
            } else {
                System.out.println("⚠️ 跳过空角色");
            }
        }

        System.out.println("🎭 最终权限列表大小: " + authorities.size());
        for (GrantedAuthority authority : authorities) {
            System.out.println("   - " + authority.getAuthority());
        }

        return authorities;
    }

    // 添加一个辅助方法用于直接查询用户信息（用于调试）
    public void debugUserInfo(String username) {
        System.out.println("\n=== 调试用户信息 ===");
        System.out.println("查询用户: " + username);

        UserDto userDto = baseMapper.selectOne(new LambdaQueryWrapper<UserDto>()
                .eq(UserDto::getStuOrTeaId, username));

        if (userDto == null) {
            System.out.println("❌ 调试: 用户不存在");
            return;
        }

        System.out.println("✅ 调试: 用户存在");
        System.out.println("ID: " + userDto.getId());
        System.out.println("学号/工号: " + userDto.getStuOrTeaId());
        System.out.println("密码: " + userDto.getUserPass());
        System.out.println("账号状态: " + userDto.getAccountStatus() + " (类型: " +
                (userDto.getAccountStatus() != null ? userDto.getAccountStatus().getClass().getSimpleName() : "null") + ")");
        System.out.println("角色: " + userDto.getRole());
        System.out.println("注册时间: " + userDto.getRegisterTime());
        System.out.println("更新时间: " + userDto.getUpdateTime());
        System.out.println("=== 调试结束 ===\n");
    }
}
